package com.zz.check;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;

public class CheckConfig {

	//包名以.分隔
	private static List<String> ignorePackages = new ArrayList<String>();
	//包名中以/分隔
	private static List<String> ignorePackages2 = new ArrayList<String>();
	private static List<String> ignoreJars = new ArrayList<String>();

	private CheckConfig(){}
	static {
		setCheckConfigByProperty("com.zz.check.CheckConfig");
	}
	
	/**
	 * 是否是需要忽略的package
	 * @param packageName
	 * @return
	 */
	public static boolean isIgnorePackage(String packageName){
		
		//包路径以/分隔
		for(String ignorePackage : ignorePackages2){
			if(packageName.startsWith(ignorePackage)){
				return true;
			}
		}
		//包路径以.分隔
		for(String ignorePackage : ignorePackages){
			if(packageName.startsWith(ignorePackage)){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 是否是需要忽略的class
	 * @param className
	 * @return
	 */
	public static boolean isIgnoreClass(String className){
		return isIgnorePackage(className);
	}
	
	/**
	 * 是否是需要忽略的jar包
	 * @param jarName
	 * @return
	 */
	public static boolean isIgnoreJar(String jarName){
 		for(String ignorejar : ignoreJars){
			if(jarName.startsWith(ignorejar)){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 通过指定properties文件路径来设置需要忽略的包和jar
	 * @param propertyFilePath
	 */
	public static void setCheckConfig(String propertyFilePath){
		setCheckConfigByProperty(propertyFilePath);
	}
	
	/**
	 * 设置需要忽略的包和jar
	 * @param ignorePackagesStr 需要忽略的包名，包名路径以.隔开,多个包以;隔开
	 * @param ignoreJarsStr 需要忽略的jar名称,以;隔开
	 */
	public static void setCheckConfig(String ignorePackagesStr,String ignoreJarsStr){
		if(ignorePackagesStr != null && !"".equals(ignorePackagesStr)){
			ignorePackagesStr = ignorePackagesStr.replace("*", "");
			if(!"".equals(ignorePackagesStr)){
				ignorePackages = Arrays.asList(ignorePackagesStr.split(";"));
			}
			ignorePackagesStr = ignorePackagesStr.replace(".", "/");
			if(!"".equals(ignorePackagesStr)){
				ignorePackages2 = Arrays.asList(ignorePackagesStr.split(";"));
			}
		}
		if(ignoreJarsStr != null && !"".equals(ignoreJarsStr)){
			ignoreJarsStr = ignoreJarsStr.replace("*", "").replace(".jar", "");
			if(!"".equals(ignoreJarsStr)){
				ignoreJars = Arrays.asList(ignoreJarsStr.split(";"));
			}
			
		}
	}
	
	private static void setCheckConfigByProperty(String propertyFilePath){
		ResourceBundle localResourceBundle = ResourceBundle.getBundle(propertyFilePath);
		String ignorePackagesString = localResourceBundle.getString("ignorePackages");
		String ignoreJarsString = localResourceBundle.getString("ingoreJars");
		setCheckConfig(ignorePackagesString,ignoreJarsString);
	}
	
	public static void main(String[] args){
		System.out.println(CheckConfig.isIgnorePackage("java.long.String"));
		System.out.println(CheckConfig.isIgnorePackage("java.util"));
		System.out.println(CheckConfig.isIgnoreJar("111.jar"));
	}
	
}
